/*
 * Copyright (c) 2011. This file is public under GPLv3 license.
 * For more information about license please refer to http://www.gnu.org/licenses/gpl.html
 */

package com.freetools.watchdog.model;

import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * Date: Feb 27, 2011
 *
 * @author Michael Morozov
 */
public class FileSource implements ISource
{
    private RandomAccessFile reader;
    private long recommendedBufferSize = 1024 * 1024;
    private Logger log = Logger.getLogger(FileSource.class);

    public File getFile()
    {
        return file;
    }

    private File file;
    private long fileSize;

    public FileSource(File file) throws FileNotFoundException
    {
        this.file = file;
        fileSize = this.file.length();
        recommendedBufferSize = fileSize < recommendedBufferSize ? fileSize : recommendedBufferSize;
        reader = new RandomAccessFile(this.file, "r");
    }

    public String read(long from, long to) throws IOException
    {
        if (from == to) return "";

        byte[] buffer = new byte[(int) (to - from)];
        reader.seek(from);
        int read = reader.read(buffer);
//        double readedInPercents = (double) to * 100 / fileSize;
//        if (readedInPercents >= 100.0)
//        {
//            reader.close();
//        }
//        UserInformation.info(readedInPercents);
        return read > 0 ? new String(buffer, 0, read) : "";
    }

    public long getRecommendedBufferSize()
    {
        return recommendedBufferSize;
    }

    @Override
    public String toString()
    {
        return this.file.toString();
    }
}
